import { defineComponent, reactive, ref } from "vue";
import Popup from "@/components/Popup/Popup";
import styles from "./Add.module.less";
import _ from "lodash";
import to from "await-to-js";
import { message } from "ant-design-vue";
export default defineComponent({
  emits: ["change"],
  setup(props, { expose, emit }) {
    const popupRef = ref(null as any);
    const state = reactive({
      actionType: "add",
      id: null,
      form: {
        name: null,
        code: null,
        status: 1,
        remark: null,
      },
      submiting: false,
    })
    const getDetail = async () => {

    }
    const open = async ({ actionType, id } = { actionType: 'add', id: null }) => {
      state.actionType = actionType;
      state.id = id;
      if (actionType === 'edit') {
        await getDetail();
      }
      popupRef.value.open();
    }
    const close = () => {
      popupRef.value.close();
    }
    const formRef = ref(null as any);
    const submit = async () => {
      formRef.value.validate()
        .then(async () => {
          state.submiting = true;
          const params = _.cloneDeep(state.form);
          const err = null;
          // const [err, res]: any = await to((state.actionType === 'edit' ? props.service?.edit : props.service?.add)(params));
          if (!err) {
            message.success(state.actionType === 'edit' ? '编辑成功' : '添加成功');
            close();
            emit('change');
          }
          state.submiting = false;
          close();
        })
    }
    expose({
      open,
      close,
    })
    return () => (
      <Popup ref={popupRef} oriState={state}>
        <div class={styles.title}>{state.actionType === 'add' ? "添加" : "修改"}字典</div>
        <div class={styles.formBox}>
          <a-form style={{ width: "100%" }} ref={formRef} model={state.form} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 28 }}>
            <a-form-item required label="字典名称" name="name">
              <a-input v-model:value={state.form.name} placeholder="请输入字典名称" />
            </a-form-item>
            <a-form-item required label="字典编码" name="code">
              <a-input v-model:value={state.form.code} placeholder="请输入字典编码" />
            </a-form-item>
            <a-form-item required label="状态" name="status">
              <a-switch v-model:checked={state.form.status} checkedValue={1} unCheckedValue={0} />
            </a-form-item>
            <a-form-item label="备注" name="remark">
              <a-textarea v-model:value={state.form.remark} placeholder="请输入备注" />
            </a-form-item>
          </a-form>
        </div>
        <div class={styles.footer}>
          <a-button type="primary" loading={state.submiting} onClick={() => { submit() }}>提交</a-button>
          <a-button onClick={() => { close() }}>取消</a-button>
        </div>
      </Popup>
    )
  }
})